<template>
  <div class="userBox bg-f2" id="uploadtu5">
    <div class="bg-fff">
      <el-breadcrumb separator-class="el-icon-arrow-right" class="pAll">
        <el-breadcrumb-item>
          <span @click="goBack" class="goTitle">电子警察列表</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ title }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="pAll">
        <el-row>
          <el-col :span="2">
            <span class="title">电子警察信息：</span>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电子警察名称:" prop="dzjcmc">
              <el-input v-model.trim="ruleForm.dzjcmc" clearable placeholder="电子警察名称"></el-input>
            </el-form-item>
            <el-form-item label="电子警察入网码:" prop="dzjcrwbm" class="form-item-bottom">
              <el-input v-model.trim="ruleForm.dzjcrwbm" clearable placeholder="电子警察入网码/编号"></el-input>
            </el-form-item>
            <el-form-item prop="glbh1" class="form-item-bottom">
              <div class="xunze">
                <span>关联编号1:</span>
                <el-input v-model.trim="ruleForm.glbh1" clearable placeholder="请输入"></el-input>
              </div>
            </el-form-item>
            <el-form-item prop="glbh2">
              <div class="xunze">
                <span>关联编号2:</span>
                <el-input v-model.trim="ruleForm.glbh2" clearable placeholder="请输入"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="辖区(安装地址):" prop="xqbm">
              <el-cascader
                v-show="showcity"
                v-model="ruleForm.xqbm"
                ref="cascaderList"
                class="inputSelect"
                clearable
                style="margin-right: 10px"
                @change="handleChange"
                @visible-change="visibleChange"
                :props="{
                  lazy: true,
                  lazyLoad: lazyLoadAdd,
                }"
              ></el-cascader>
              <el-input
                v-show="!showcity"
                v-model="xianxidizhi"
                class="inputSelect"
                disabled
                style="margin-right: 10px"
              ></el-input>
              <el-button
                class="btnSizeStyle"
                type="primary"
                plain
                size="small"
                @click="selectCity"
              >选择</el-button>
              <div
                v-show="title === '编辑电子警察' && ruleForm.isbind"
                style="color: #f56f6f;"
              >修改辖区后,该电子警察所绑定的一切设备将被解除绑定,请谨慎修改</div>
            </el-form-item>
            <!-- <el-form-item label="辖区编码:">
              <el-input v-model.trim="ruleForm.xqbm2" disabled placeholder="辖区编码"></el-input>
            </el-form-item>-->
            <el-form-item label="详细地址:">
              <el-input
                clearable
                type="textarea"
                :rows="4"
                :maxlength="100"
                resize="none"
                show-word-limit
                v-model.trim="ruleForm.xxdz"
                placeholder="请输入设备安装详细地址信息"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="3">
            <el-form-item label="坐标(经度/纬度):" prop="gpszb">
              <el-input
                clearable
                v-model.trim="ruleForm.gpszb"
                placeholder="00.000000，000.000000"
                class="inputSelect"
              ></el-input>
              <el-tooltip content="输入经纬度，并以英文逗号隔开" placement="top-start" effect="light">
                <i class="el-icon-warning-outline iconBtn"></i>
              </el-tooltip>
              <div class="jinDuTitle">请填写度格式的值（绑定前卫主机可自动获取）</div>
            </el-form-item>
            <el-form-item prop="NE">
              <div class="DuFen">
                <el-input v-model.trim="ruleForm.NE" clearable placeholder="度分格式"></el-input>
                <el-button
                  type="primary"
                  size="medium"
                  class="btnGs btnSizeStyle"
                  :disabled="ruleForm.NE === '' ? true : false"
                  @click="geZhuanhuan"
                  v-preventReClick
                >格式转换</el-button>
                <el-input v-model.trim="ruleForm.NE2" clearable placeholder="度格式"></el-input>
                <el-tooltip content="度格式的值请填写到资产坐标" placement="top-start" effect="light">
                  <i class="el-icon-warning-outline iconBtn"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="竣工图:">
              <el-upload
                action="#"
                ref="upload"
                list-type="picture-card"
                :auto-upload="false"
                accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PNG"
                :on-change="lalal"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
              <span class="el-upload__tip">只能上传jpg/png文件，且不超过2M</span>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="fooer_btn">
          <el-button class="btnSizeStyle" size="medium" @click="goBack">取消</el-button>
          <el-button
            class="btnSizeStyle"
            type="primary"
            :loading="goliebiao"
            size="medium"
            @click="baoCun(title, 'ruleForm')"
            v-preventReClick
          >保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getUrl, setUrl } from '@/utils/getUrl.js'
import { linkageCity } from '@/utils/linkageCity.js'
import { ziC, upload } from '@/utils/allUrl.js'
import { startLoading, endLoading } from '@/utils/loading.js'
export default {
  data: function() {
    return {
      radio: '单个添加',
      ruleForm: {
        dzjcmc: '',
        dzjcrwbm: '',
        glbh1: '',
        glbh2: '',
        xqbm: '',
        xqbm2: '',
        xxdz: '',
        gpszb: '',
        NE: '',
        NE2: ''
      },
      rules: {
        dzjcmc: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        dzjcrwbm: [
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/g, message: '请输入数字或者字母', trigger: 'blur' }
        ],
        xqbm: [{ required: true, message: '此处为必填项', trigger: 'change' }],
        glbh1: [
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/, message: '请输入数字或者字母', trigger: 'blur' }
        ],
        glbh2: [
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/, message: '请输入数字或者字母', trigger: 'blur' }
        ],
        gpszb: [{ pattern: /^[,.0-9]*$/, message: '请输入以英文逗号分隔的数字', trigger: 'blur' }],
        NE: [{ pattern: /^[,.0-9]*$/, message: '请输入以英文逗号分隔的数字', trigger: 'blur' }]
      },
      title: '', // 标题
      //  图片上传
      imgUrl: [],
      fileList: [], // 上传列表
      dialogVisible: false,
      dialogImageUrl: '', // 预览
      goliebiao: false, // 防重复点击
      xianxidizhi: '',
      showcity: false,
      xqbmValue: '',
      diziValue: ''
    }
  },
  created: function() {
    const { title, content } = this.$route.query
    this.title = title
    if (content) {
      this.setList(content)
      // this.tableisShow = true
      // this.getChakanList(content.id)
    } else {
      // this.tableisShow = false
    }
  },
  methods: {
    // async lazyLoadAdd(node, resolve) {
    //   if (node.level === 0) {
    //     return resolve(await linkageCity())
    //   } else if (node.level === 1) {
    //     return resolve(await linkageCity(node.level + 1, node.value))
    //   } else if (node.level === 2) {
    //     return resolve(await linkageCity(node.level + 1, node.value))
    //   } else if (node.level === 3) {
    //     return resolve(await linkageCity(node.level + 1, node.value, node.label))
    //   }
    // },
    async setList(id) {
      const user = JSON.parse(getUrl('userconter'))
      const params = new URLSearchParams()
      params.append('userId', user.id)
      // params.append('JGID', user.zzjg_ID)
      params.append('ID', id)
      const { data: res } = await this.$http.post(`${ziC}dzjc/selectDianZiJingCha`, params)
      if (res.code === '0000') {
        const content = res.data.list[0]
        if (content.jgt) {
          const cao = content.jgt.replace(/uid/g, 'name')
          this.fileList = JSON.parse(cao)
          this.imgUrl = this.fileList
        }
        this.ruleForm = content
        this.ruleForm.xqbm2 = content.ssq_NO
        this.ruleForm.xqbm = content.ssq_NO - ''
        this.xianxidizhi = content.sfmc + ' / ' + content.csmc + ' / ' + content.xqmc + ' / ' + content.jdmc
      } else {
        this.ruleForm = []
      }
    },
    async lazyLoadAdd(node, resolve) {
      const user = JSON.parse(getUrl('userconter'))
      if (node.level === 0) {
        return resolve(await linkageCity(user.id, node.level + 1))
      } else if (node.level === 1) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 2) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 3) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value, node.label))
      }
    },
    //   辖区编码
    handleChange(e) {
      this.$nextTick(() => {
        const vals = this.$refs.cascaderList.presentText
        if (vals) {
          this.xianxidizhi = vals
        } else {
          this.xianxidizhi = this.diziValue
        }
      })
      if (e.length === 1) {
        this.ruleForm.xqbm2 = e[0]
      } else if (e.length === 2) {
        this.ruleForm.xqbm2 = e[1]
      } else if (e.length === 3) {
        this.ruleForm.xqbm2 = e[2]
      } else if (e.length === 4) {
        this.ruleForm.xqbm2 = e[3]
      } else if (e.length === 0) {
        this.ruleForm.xqbm2 = ''
        this.showcity = false
        this.ruleForm.xqbm = this.xqbmValue
      }
    },
    // 格式转换
    async geZhuanhuan() {
      const params = new URLSearchParams()
      params.append('NE', this.ruleForm.NE)
      const { data: res } = await this.$http.post(`${ziC}kakou/changeGPS`, params)
      if (res.code === '0014') {
        return
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true
        })
      }
      this.$message({
        type: 'success',
        message: res.message,
        center: true
      })
      this.ruleForm.NE2 = res.data.NE
      this.ruleForm.gpszb = res.data.NE
    },
    // 删除图片
    handleRemove(a) {
      const index = this.imgUrl.findIndex(item => item.uid === a.uid)
      this.imgUrl.splice(index, 1)
    },
    // 添加图片
    async lalal(el) {
      let videoSize = el.size / (1024 * 1024) // 转成M格式
      videoSize = videoSize.toFixed(1) // 保留小数点后一位
      if (videoSize > 2) {
        const dele = this.$refs.upload.uploadFiles
        const index = dele.findIndex(item => item.uid === el.uid)
        dele.splice(index, 1)
        // this.$refs.upload.uploadFiles
        return this.$message({
          type: 'error',
          message: '图片超过最大限制2M',
          center: true
        })
      } else {
        startLoading(document.getElementById('uploadtu5'))
        const file = el.raw
        const fd = new FormData()
        let arr = {}
        fd.append('file', file) // 传文件
        fd.append('type', 1) // 传文件
        const { data: res } = await this.$http.post(`${upload}`, fd)
        endLoading()
        if (res.code === '0000') {
          res.data.forEach(item => {
            arr = {
              uid: el.uid,
              url: item
            }
          })
          this.imgUrl.push(arr)
        } else {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true
          })
        }
      }
    },
    // 预览
    handlePictureCardPreview(e) {
      this.dialogImageUrl = e.url
      this.dialogVisible = true
    },
    baoCun(title, ruleForm) {
      this.goliebiao = true
      const a = setTimeout(() => {
        this.goliebiao = false
      }, 10000)
      const user = JSON.parse(getUrl('userconter'))
      const { dzjcmc, dzjcrwbm, glbh1, glbh2, xqbm, xqbm2, xxdz, gpszb, id } = this.ruleForm
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (title === '添加电子警察') {
            const params = new URLSearchParams()
            params.append('user_id', user.id)
            params.append('JGID', user.zzjg_ID)
            params.append('DZJCMC', dzjcmc)
            params.append('DZJCRWBM', dzjcrwbm)
            params.append('GLBH1', glbh1)
            params.append('GLBH2', glbh2)
            params.append('XQBM', xqbm2 || 0)
            params.append('XXDZ', xxdz)
            params.append('GPSZB', gpszb)
            params.append('JGT', JSON.stringify(this.imgUrl))
            if (xqbm.length === 3) {
              params.append('SFBM', xqbm[0])
              params.append('CSBM', xqbm[1])
              params.append('XQBM', xqbm[2])
              params.append('SSQ_NO', xqbm[2])
            } else if (xqbm.length === 4) {
              params.append('SFBM', xqbm[0])
              params.append('CSBM', xqbm[1])
              params.append('XQBM', xqbm[2])
              params.append('JDBM', xqbm[3])
              params.append('SSQ_NO', xqbm[3])
            }
            const { data: res } = await this.$http.post(`${ziC}dzjc/insertDianZiJingCha`, params)
            if (res.code === '0014') {
              return
            } else if (res.code !== '0000') {
              clearTimeout(a)
              this.goliebiao = false
              return this.$message({
                type: 'error',
                message: res.message,
                center: true
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true
            })
            this.goBack()
          } else {
            const params2 = new URLSearchParams()
            if (typeof xqbm !== 'number') {
              if (xqbm.length === 3) {
                params2.append('SFBM', xqbm[0])
                params2.append('CSBM', xqbm[1])
                params2.append('XQBM', xqbm[2])
                params2.append('SSQ_NO', xqbm[2])
              } else if (xqbm.length === 4) {
                params2.append('SFBM', xqbm[0])
                params2.append('CSBM', xqbm[1])
                params2.append('XQBM', xqbm[2])
                params2.append('JDBM', xqbm[3])
                params2.append('SSQ_NO', xqbm[3])
              }
            } else {
              const s = (xqbm + '').substr(0, 2) + '0000'
              const c = (xqbm + '').substr(0, 4) + '00'
              const x = (xqbm + '').substr(0, 6)
              params2.append('SFBM', s)
              params2.append('CSBM', c)
              params2.append('XQBM', x)
              if ((xqbm + '').length > 6) {
                params2.append('JDBM', xqbm)
                params2.append('SSQ_NO', xqbm)
              } else {
                params2.append('SSQ_NO', x)
              }
            }
            params2.append('ID', id)
            params2.append('user_id', user.id)
            params2.append('JGID', user.zzjg_ID)
            params2.append('DZJCMC', dzjcmc)
            params2.append('DZJCRWBM', dzjcrwbm)
            params2.append('GLBH1', glbh1)
            params2.append('GLBH2', glbh2)
            params2.append('XQBM', xqbm2 || 0)
            params2.append('XXDZ', xxdz)
            params2.append('GPSZB', gpszb)
            params2.append('JGT', JSON.stringify(this.imgUrl))
            const { data: res } = await this.$http.post(`${ziC}dzjc/updateDianZiJingCha`, params2)
            if (res.code === '0014') {
              return
            } else if (res.code !== '0000') {
              clearTimeout(a)
              this.goliebiao = false
              return this.$message({
                type: 'error',
                message: res.message,
                center: true
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true
            })
            this.goBack()
          }
        } else {
          this.goliebiao = false
          this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true
          })
          return false
        }
      })
    },
    // 最大车速
    inputMax(num) {
      if (num > 220) {
        this.ruleForm.xxcxs = '220'
      }
    },
    inputMax2(num) {
      if (num > 220) {
        this.ruleForm.dxcxs = '220'
      }
    },
    goBack: function() {
      setUrl('bayonet', 'electronicPolice')
      this.$router.push('/electronicPolice')
      // this.chedaoOptions.forEach(item => {
      //   item.disabled = false
      // })
    },
    selectCity() {
      // this.JointSelection.dialogWorkOrder = true
      this.showcity = true
      this.$refs.cascaderList.toggleDropDownVisible()
    },
    visibleChange(val) {
      if (!val) {
        // if (this.ruleForm.xqbm === this.xqbmValue) {
        //   this.showcity = false
        // }
        this.showcity = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
// ::v-deep tr {
//   height: '38px' !important;
// }
.userBox {
  .el-row {
    // padding: 15px 25px 0 25px;
    border-bottom: 1px solid #f2f2f2;
    .title {
      display: block;
      height: 38px;
      line-height: 38px;
      color: rgba(89, 89, 89, 1);
      font-size: 15px;
      font-weight: 600;
    }
    .el-form-item {
      .inputSelect {
        width: 260px;
      }
      .jinDuTitle {
        height: 18px;
        line-height: 22px;
        color: #c0c4cc;
      }
      .iconBtn {
        margin-left: 10px;
        font-size: 15px;
        color: rgba(187, 187, 187, 1);
        cursor: pointer;
      }
      .DuFen {
        display: flex;
        justify-content: space-around;
        align-items: center;
        .btnGs {
          margin: 0 10px;
        }
      }
      .el-upload__tip {
        font-size: 12px;
        color: #a1a3a8;
        margin-top: 7px;
        padding-left: 10px;
      }
      .xunze {
        margin-top: 18px;
        display: flex;
        > span {
          color: #333;
          width: 80px;
          margin-right: 10px;
        }
      }
    }
    .form-item-bottom {
      margin-bottom: 0;
    }
  }
  .fooer_btn {
    margin: 10px 0;
    display: flex;
    justify-content: flex-end;
  }
  .dialogTitle {
    font-size: 15px;
    font-weight: 600;
  }
  .addSheBei {
    // display: flex;
    // justify-content: space-between;
    > li:first-child {
      // margin-left: 0;
      float: left;
    }
    > li {
      height: 35px;
      line-height: 35px;
      float: right;
      .selectItem3 {
        width: 250px;
      }
      .addShebSearch {
        margin-left: 10px;
      }
    }
    .select2 {
      > span {
        font-weight: 600;
        margin-right: 5px;
      }
      .selectItem2 {
        width: 300px;
        line-height: 0;
      }
    }
  }
  .zhujiBox {
    > li {
      height: 40px;
      // line-height: 40px;
      // padding: 20px 0;
      display: flex;
      align-items: center;
      // justify-content: center;
      // border-bottom: 1px solid #ebeef5;
      .zhujiBoxTitle {
        // line-height: 40px;
        position: relative;
        // top: 0;
        left: 10%;
      }
      .zhujiBoxSelect1 {
        width: 25%;
        position: absolute;
        // top: 0;
        left: 64%;
      }
      .zhujiBoxSelect2 {
        width: 16%;
        position: absolute;
        // top: 0;
        right: 1%;
      }
    }
  }
  .cneterNull {
    display: flex;
    justify-content: center;
  }
}
</style>
